<template>
    <div class="login-container">
        <!-- 左侧文字区域 -->
        <div class="left-section">
            <h1 class="main-title">
                <span class="zh">软件造价评估平台</span><br>
                <span class="en" style="font-size: 22px;">Software Cost Estimation Platform</span>
            </h1>

        </div>

        <!-- 右侧登录表单区域 -->
        <div class="right-section">

            <el-tabs v-model="activeTab" class="login-form-tabs" :stretch="true">
                <!-- 登录表单 -->
                <el-tab-pane label="登录" name="login">
                    <el-form ref="ruleFormRef" :model="loginForm" label-width="60px" class="login-form" status-icon>
                        <h3 style="font-weight: bold;">登录</h3>
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="loginForm.username" placeholder="请输入用户名" />
                        </el-form-item>

                        <el-form-item label="密码" prop="password">
                            <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" />
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" plain @click="onSubmitLogin" style="width: 200px;">登录</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>

                <!-- 注册表单 -->
                <el-tab-pane label="注册" name="register">
                    <el-form ref="registerFormRef" :model="registerForm" label-width="60px" class="login-form"
                        status-icon>
                        <!-- <h4 style="font-weight: bold;">注册</h4> -->

                        <el-radio-group v-model="registerForm.registerType">
                            <el-radio label="phone">手机号注册</el-radio>
                            <el-radio label="email">邮箱注册</el-radio>
                        </el-radio-group>
                        <el-form-item label="租户" prop="tenantName">
                            <el-input v-model="registerForm.tenantName" placeholder="请输入租户名称" />
                        </el-form-item>
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="registerForm.username" placeholder="请输入用户名" />
                        </el-form-item>
                        <el-form-item v-if="registerForm.registerType === 'phone'" label="手机号" prop="phone">
                            <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
                        </el-form-item>

                        <el-form-item v-if="registerForm.registerType === 'email'" label="邮箱" prop="email">
                            <el-input v-model="registerForm.email" placeholder="请输入邮箱" />
                        </el-form-item>

                        <el-form-item label="验证码" prop="captcha">
                            <el-input v-model="registerForm.captcha" placeholder="请输入验证码" />
                            <el-button type="primary" @click="sendCaptcha" style="margin-top: 10px;"
                                plain>发送验证码</el-button>
                        </el-form-item>

                        <el-form-item label="密码" prop="password">
                            <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" />
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" plain @click="onSubmitRegister"
                                style="width: 200px;">注册</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
    <!-- 使用 transition 包裹验证码组件 -->
    <transition name="verify">
        <Verify v-if="enableCaptcha" @success="login" @error="loadVerify" ref="verifyRef" :mode="'pop'"
            :captchaType="captchaType" :imgSize="{ width: '330px', height: '155px' }">
        </Verify>
    </transition>
</template>

<script setup lang="ts">
import Verify from '../components/verifition/Verify.vue';
import { ref, useTemplateRef, nextTick, watch } from 'vue'
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus'
import { Userlogin, getLoginInfo, UserRegister, sendCaptchaInfo } from '../api/Tenant/userApi.ts'
import { useRouter } from 'vue-router';
import { useTokenStore } from '../stores/token';
import { useUserStore } from '../stores/UserStore'
const tokenStore = useTokenStore();
const userStore = useUserStore();
const router = useRouter();
const loginForm = ref({
    username: '',
    password: ''
})


const enableCaptcha = ref(false)
//const verifyRef = ref<InstanceType<typeof Verify>>()
const verifyRef = useTemplateRef<InstanceType<typeof Verify>>("verifyRef")
const captchaType = ref<string>('blockPuzzle')
// 随机加载滑块/点击验证码
const loadVerify = () => {
    setTimeout(() => {
        captchaType.value = Math.random() < 0.5 ? 'blockPuzzle' : 'clickWord';
    }, 700)

}
// 显示验证码
const showVerify = () => {
    if (verifyRef.value) {
        verifyRef.value.show();
    } else {
        console.error('verifyRef is undefined');
    }
}


const activeTab = ref('login');


const onSubmitLogin = async () => {
    if (!loginForm.value.username || !loginForm.value.password) {
        ElMessage.error('请输入完整的登录信息');
        return;
    }
    enableCaptcha.value = true;
    await nextTick();  // 等待 DOM 更新
    showVerify();

};
const login = async () => {
    const res = await Userlogin(loginForm.value.username, loginForm.value.password);
  
    tokenStore.setToken(res);
    
    // 检查是否有邀请 Token
    if (userStore.invitationToken) {
        const token = userStore.invitationToken;
        userStore.setInvitationToken(null); // 清除 Token
        router.push({ name: 'InvitationAccept', query: { token } }); // 重定向到邀请页面
    } else {
        setTimeout(async() => {
            const userInfo = await getLoginInfo();
            userStore.setUserInfo(userInfo);
        }, 900);
        setTimeout(() => {
            ElMessage.success('登录成功');
            router.push('/home');
        }, 100);
    }

}


// 注册表单
const registerForm = ref({
    registerType: 'phone', // 注册方式，默认为手机号注册
    phone: '',
    email: '',
    captcha: '',
    password: '',
    username: '',
    tenantName: ''
});
//监听
watch(
    () => registerForm.value.username,
    () => {
        // 当 tenantIdList 发生变化时，重新获取项目数据
        registerForm.value.captcha = ''
    }
);


const sendCaptcha = async () => {
    if (!registerForm.value.username) {
        ElMessage.error('请输入用户名');
        return;
    }
    if (registerForm.value.registerType === 'phone' && !registerForm.value.phone) {
        ElMessage.error('请输入手机号');
        return;
    }
    if (registerForm.value.registerType === 'email' && !registerForm.value.email) {
        ElMessage.error('请输入邮箱');
        return;
    }
    ElMessage.success('验证码已发送，请查收');
    await sendCaptchaInfo(registerForm.value);

};

const onSubmitRegister = async () => {
    if (registerForm.value.registerType === 'phone' && !registerForm.value.phone) {
        ElMessage.error('请输入手机号');
        return;
    }
    if (registerForm.value.registerType === 'email' && !registerForm.value.email) {
        ElMessage.error('请输入邮箱');
        return;
    }
    if (!registerForm.value.captcha || !registerForm.value.password) {
        ElMessage.error('请填写完整的注册信息');
        return;
    }
    await UserRegister(registerForm.value);
    ElMessage.success('注册成功');
    activeTab.value = 'login';
    reset();
};

const reset = () => {
    registerForm.value.registerType = 'phone';
    registerForm.value.email = '';
    registerForm.value.captcha = '',
        registerForm.value.password = '',
        registerForm.value.username = '',
        registerForm.value.tenantName = ''
}
</script>

<style scoped>
/* 确保 html 和 body 占满整个视口 */
html,
body {
    height: 90%;
    margin: 0;
    padding: 0;
}

/* 设置整个页面的背景图片 */
.login-container {
    display: flex;
    height: 100vh;
    /* 使用视口高度 */
    width: 100vw;
    /* 让宽度占满整个视口 */
    background-image: url('../assets/back.png');
    background-size: cover;
    /* 确保图片填充整个区域并裁剪 */
    background-position: center bottom;
    /* 图片居中并靠下对齐 */
    background-repeat: no-repeat;
    /* 防止图片重复 */

}

/* 左侧区域样式 */
.left-section {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 16px;
    font-weight: bold;

}

/* 右侧区域样式 */
.right-section {
    width: 500px;
    height: 90%;
    margin-right: 100px;
    /* background-color: rgba(255, 255, 255, 0.8); */
    padding: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.login-form-tabs {
    font-size: 18px;
    /* 设置字体大小 */
    display: flex;
    justify-content: space-between;
    width: 300px;
    margin-left: 10px;
    margin-right: 50px;
    height: 420px;
    max-width: 350px;
    padding: 20px;
    background: linear-gradient(135deg, #eae6ff, #c5d0fb);
    /* 紫色到蓝色的渐变背景 */
    /* 纯白背景 */
    border-radius: 30px;
    /* 圆角样式 */
    box-shadow: 0 8px 18px rgba(0, 0, 0, 0.1);
    /* 轻微阴影效果 */

}

/* 表单样式 */
.login-form {}

.el-tabs {
    text-align: center;
    margin-left: 20px;
}

/* 表单输入框样式 */
.el-input {
    width: 200px;
    border-radius: 30px;

    /* 圆角样式 */
}

.el-button {
    border-radius: 8px;
    /* 圆角样式 */
}

/* 初始状态：元素在视图之外 */
.verify-enter-from {
    transform: translateY(5px);
    opacity: 0;
}

.slide-enter-active {
    transform: translateY(0);
    opacity: 1;
    transition: all 0.5s ease-in-out;
}

/* 离开状态：元素滑出视图 */
.slide-leave-to {
    opacity: 0;
}

.slide-leave-active {
    transition: all 0.2s ease-out;

}
</style>